<%--
  Created by IntelliJ IDEA.
  User: s1xgod
  Date: 2022/9/30
  Time: 13:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>上传</title>
    <link rel="shortcut icon" href="/res/favicon.ico" type="image/x-icon">
    <link rel="stylesheet" href="../layui/css/layui.css">
    <link rel="stylesheet" href="../css/register.css">
    <script src="../js/jquery-3.6.1.min.js"></script>
    <script src="../layui/layui.js"></script>
    <%--    该页面不是用子窗口打开的，跳转到登录界面--%>
    <script>
        if (window == top) {
            location.href = "/res/user/login.jsp";
        }
    </script>
</head>
<body>
<div>
    <div id="文字标题">文件上传（最大10Mb）</div>
    <div>目前仅支持在线预览图片/.txt/.doc/.ppt/.xls/.pdf文件</div>
    <br>
    <form class="layui-form layui-form-pane" action="" method="post">
        <div id="login-name-check" style="position: absolute;top: 45px;left: 200px;color: red"></div>
        <br>
        <div class="layui-form-item">
            <label class="layui-form-label">新文件名</label>
            <div class="layui-input-inline">
                <input id="file-name" type="text" name="fileName" required lay-verify="required|okFileName"
                       placeholder="请输入新文件名"
                       autocomplete="off"
                       class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux"></div>
        </div>
        <div class="layui-form-item" style="display: none">
            <label class="layui-form-label">文件类型</label>
            <div class="layui-input-inline">
                <input id="file-type" type="text" name="fileType" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux"></div>
        </div>
        <div class="layui-form-item" style="display: none">
            <label class="layui-form-label">文件大小</label>
            <div class="layui-input-inline">
                <input id="file-bytes" type="text" name="fileBytes" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux"></div>
        </div>

        <div class="layui-form-item" style="display: none">
            <label class="layui-form-label">用户id</label>
            <div class="layui-input-inline">
                <input id="userid" type="text" name="userId" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux"></div>
        </div>

        <div class=" layui-form-item">
            <label class="layui-form-label">描述</label>
            <div class="layui-input-inline">
                <input id="remark" type="text" name="remark" required lay-verify="required|okRemark"
                       placeholder="请输入文件描述"
                       autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">验证码</label>

            <div class="layui-input-inline" style="width: 100px">
                <input type="text" name="code" required lay-verify="required" placeholder="请输入验证码"
                       autocomplete="off" class="layui-input">
            </div>
            <img id='codeImg' src="/common/code?type=2">
            <div class="layui-form-mid layui-word-aux"></div>
        </div>
        <div class="layui-upload-drag" id="test10" style="width: 300px">
            <div id="desc">点击上传，或将文件拖拽到此处</div>
            <i class="layui-icon"></i>
            <div class="layui-hide" id="uploadDemoView">
                <hr>
                <%--        <img src="" alt="上传成功后渲染" style="max-width: 196px">--%>
            </div>
            <div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="demo">
                <div class="layui-progress-bar" lay-percent=""></div>
            </div>
        </div>
        <br>
        <br>

        <div class="layui-form-item submit-btn">
            <div class="layui-input-inline">
                <button id="submit" class="layui-btn" lay-submit lay-filter="formDemo">确认</button>
                <span style="margin-left: 20px;margin-right: 20px"></span>
                <button id="reset" type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
    <button id="uploadHidden" style="display: none">隐藏按钮</button>
</div>


</body>
<script>
    console.log("${user.id}")
    layui.use(['form', 'upload', 'element', 'layer'], function () {
        var $ = layui.jquery
            , form = layui.form
            , upload = layui.upload
            , element = layui.element
            , layer = layui.layer;
        var fileId = '';
        var filename = '';
        var fileIsChoosed = false;
        // 传入拖拽上传的对象
        var ob = {
            elem: '#test10'
            , size: 10000
            , url: '/common/upload' //此处用的是第三方的 http 请求演示，实际使用时改成您自己的上传接口即可。
            , accept: 'file'
            , exts: 'jpg|png|gif|bmp|jpeg|pdf|ppt|doc|docx|xlsx|xls|pptx|ppt|txt'
            , auto: false // 不自动上传
            , number: 1
            , bindAction: '#uploadHidden'
            , choose: function (obj) {
                if ($("#file-name").val() == "") {
                    layer.msg("请先输入文件名")
                } else {
                    //预读本地文件
                    obj.preview(function (index, file, result) {
                        for (let i in obj.pushFile()) {
                            delete obj.pushFile()[i]
                        }
                        console.log("文件选择对象:" + file.toString()); //得到文件对象
                        // 文件名
                        filename = guid() + "." + $("#file-name").val();
                        // 文件类型
                        $("#file-type").val(file.name.substring(file.name.lastIndexOf("."), file.name.length));
                        // 文件大小
                        $("#file-bytes").val(file.size);
                        // 上传的用户id
                        $("#userid").val("${user.id}")
                        // 上传框文件展示
                        $("#desc").text($("#file-name").val() + file.name.substring(file.name.lastIndexOf("."), file.name.length));
                        fileIsChoosed = true;
                        layer.msg("读取成功", {icon: 1});
                        $("#file-name").prop("disabled", "disabled")
                        // 传去后台的文件名前面带用户名.
                        obj.resetFile(index, file, "${user.id}" + "." + filename + $("#file-type").val()); //重命名文件名，layui 2.3.0 开始新增
                    });
                }
            }
            , before: function (obj) {
                element.progress('demo', '0%'); //进度条复位
            }
            ,
            done: function (res) {
                console.log("文件上传结果:" + res.toString())
                if (res.code == "200") {
                    layer.msg('上传完毕', {icon: 1});
                } else {
                    layer.msg("文件上传失败，服务器繁忙")
                    deleteFileInfo();
                }
                //获取当前触发上传的元素，一般用于 elem 绑定 class 的情况，注意：此乃 layui 2.1.0 新增
                // var item = this.item;
            }
            ,
            error: function (index, upload) {
                layer.msg("上传失败");
                deleteFileInfo();
            }
            //进度条
            ,
            progress: function (n, elem, e) {
                element.progress('demo', n + '%'); //可配合 layui 进度条元素使用
            }
        };

        //拖拽上传
        upload.render(ob);

        // 根据文件id删除数据库中文件信息
        function deleteFileInfo() {
            $.get("/document/delete", {"id": fileId, "flag": "0"}
                , function (returnData) {
                    console.log("删除结果:" + returnData.toString())
                    if (returnData == "1") {
                        layer.msg("文件上传失败，请重试")
                    }
                })
        }

        // 验证码点击刷新,编辑界面的code类型为2
        $("#codeImg").click(function () {
            $("#codeImg").attr("src", "/common/code/?type=2&time=" + new Date().getTime());
        })

        form.verify({
            okFileName: [
                /^[a-zA-Z0-9\u4E00-\u9FA5]{1,10}$/
                , '文件名请输入长度为1-10的英文/数字/汉字'
            ],
            okRemark: [
                /^[a-zA-Z0-9\u4E00-\u9FA5]{1,50}$/
                , '文件描述请输入长度为1-50的英文/数字/汉字'
            ],
        })
        $("#reset").click(function () {
            location.href = 'upload.jsp'
        })

        // 上传该文件信息到服务器数据库
        form.on('submit(formDemo)', function (data) {
            data.field.fileName = filename;
            // 如果文件已选择才可以发送文件信息
            if (fileIsChoosed) {
                console.log(data.field.toString())
                $.ajax({
                        async: true,
                        type: 'post',
                        url: '/document/upload',
                        dataType: 'json',
                        data: data.field,
                        success: function (returnData) {
                            if (returnData.code == "200") {
                                fileId = returnData.documentInf.id;
                                $("#uploadHidden").click();
                                $("#codeImg").click();
                            } else if (returnData.code == '1') {
                                layer.msg("验证码有误");
                            } else {
                                layer.msg("服务器繁忙，操作失败");
                            }
                        },
                        error: function () {
                            //失败进入的函数
                            console.log("操作失败了")
                        }
                    }
                );
            } else {
                layer.msg("请先选择要上传的文件")
            }
            return false;
        });
    })
    ;

    function guid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0,
                v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }
</script>
</html>
